package com.kaili.controller.web.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.common.exception.BaseExcept;
import com.kaili.common.util.FreemarkUtils;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.db.service.IHsEwbsDispatchDetailService;
import com.kaili.db.service.IHsEwbsStowageDetailService;
import com.kaili.db.service.IHsOptArriveService;
import com.kaili.except.ResponseStatus;
import com.kaili.feign.UserFeignClient;
import com.kaili.pojo.dto.arrive.ArriveAddDTO;
import com.kaili.pojo.dto.arrive.ArriveCancelDTO;
import com.kaili.pojo.dto.arrive.ArrivePrintNumberDTO;
import com.kaili.pojo.dto.arrive.ArriveQueryDTO;
import com.kaili.pojo.entity.HsEwbsStowageDetail;
import com.kaili.pojo.vo.ArriveEwbVO;
import com.kaili.pojo.vo.StowageVO;
import com.kaili.utils.DateUtils;
import com.kaili.version.ApiVersion;
import freemarker.template.Configuration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Pattern;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @AUTHOR pengdongxu.
 * @Date: 18-5-14 上午9:13.
 * @COPYRIGHT 杭州凯立
 */

@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "到件服务", description = "到件服务API")
@Validated
@RestController
public class ArriveBasicController {

    @Autowired
    private IHsOptArriveService hsOptArriveService;
    @Autowired
    private IHsEwbsDispatchDetailService dispatchService;
    @Autowired
    private IHsEwbsStowageDetailService ewbsStowageDetailService;
    @Autowired
    private Configuration configuration;
    @Autowired
    private UserFeignClient userFeignClient;


    @GetMapping("/stowageDetails")
    @ApiOperation("获取配载单详情")
    public Page<ArriveEwbVO> queryArriveEwb(@Validated @ModelAttribute ArriveQueryDTO req){
        if (req.getCur()!=null && req.getPageSize() !=null){
            Page<ArriveEwbVO> pager = new Page<>(req.getCur(),req.getPageSize());
            try {
                Map<Object, Object> search = new HashMap<>();
                search.putAll(new org.apache.commons.beanutils.BeanMap(req));
                pager = hsOptArriveService.queryArriveEwb(pager, search);
                return pager;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        throw new BaseExcept(ResponseStatus.STOWAGE_QUERY_ERR);
    }

    @ApiOperation("BS/APP运单到件")
    @PostMapping("/arrives/ewbs/bat")
    public ResponseStatus doEwbArriveConfirm(@Validated @RequestBody ArriveAddDTO req){
        boolean ret = hsOptArriveService.doEwbArriveConfirm(req);
        if (ret){
            return ResponseStatus.RESPONSE_OK;
        }
        return ResponseStatus.ADD_FAIL;
    }

    @ApiOperation("打印次数")
    @PutMapping("/arrives/printNumber")
    public ResponseStatus updatePrintStowage(@Validated @RequestBody ArrivePrintNumberDTO req){
        if (req.getFirstPrintTime() !=null){
            req.setLastPrintTime(DateUtils.getNowDate());
        }else {
            req.setFirstPrintTime(DateUtils.getNowDate());
        }
        int ret = hsOptArriveService.updatePrintStowage(req);
        if (ret != -1){
            return ResponseStatus.RESPONSE_OK;
        }
        return ResponseStatus.OUT_ERROR;
    }

    @ApiOperation("配载单取消到件")
    @PutMapping("/arrives/stowageArriveCanCel")
    public ResponseStatus doStowageArriveCanCel(@RequestBody List<ArriveCancelDTO> req)throws BaseExcept{
        Map<String, Object> map = new HashMap<>();
        for (ArriveCancelDTO arriveCancelDTO : req) {
            map.put("operation_id", arriveCancelDTO.getOperationId());
            List<HsEwbsStowageDetail> ewbsStowageDetails = ewbsStowageDetailService.queryEwbByStowage(map);
            for (HsEwbsStowageDetail ewbs : ewbsStowageDetails) {
                map.put("ewbNo", ewbs.getEwbNo());
                if(dispatchService.isDispatchOrSign(map)){
                    return ResponseStatus.DISPATCH_STATUS_ALL;
                }
            }
        }
        boolean ret = hsOptArriveService.doStowageArriveCancel(req);
        if (!ret){
            return ResponseStatus.ARRIVE_CANCEL_EWB;
        }
        return ResponseStatus.RESPONSE_OK;
    }

    @ApiOperation("BS/APP运单取消到件,目前至取消库存，到件记录存在")
    @PutMapping("/arrives/ewbArriveCanCel")
    public ResponseStatus doEwbArriveCanCel(@Validated @RequestBody ArriveCancelDTO req)throws BaseExcept{
        if (req == null || req.getEwbNos().isEmpty() || req.getEwbNos().size()<=0) {
            throw new BaseExcept(ResponseStatus.EWB_EMPTY);
        }

        Map<String, Object> map = new HashMap<>();
        for (String ewbNo : req.getEwbNos()) {
            map.put("ewbNo", ewbNo);
            if(dispatchService.isDispatchOrSign(map)){
                return ResponseStatus.DISPATCH_STATUS_ALL;
            }
        }

        boolean ret = hsOptArriveService.doEwbArriveCanCel(req);
        if (!ret){
            return ResponseStatus.ARRIVE_CANCEL_EWB;
        }

        return ResponseStatus.RESPONSE_OK;
    }

    @GetMapping("/arrives/html")
    @ApiOperation(value = "获取到货单信息打印")
    public String queryPrintArriveEwb(@RequestParam("stowageNo") @ApiParam(value="到货单号逗号连接字符串",defaultValue = "0000011111") String stowageNo) throws Exception {
        if(StringUtils.isEmpty(stowageNo)){
            throw new BaseExcept(ResponseStatus.PRINT_NULL);
        }
        String logo = userFeignClient.getCompanyLogo(Long.parseLong(LoginDetailUtils.getCompanyCode()));
        JSONObject json= JSON.parseObject(logo);
        List<String> stowageList = Arrays.asList(stowageNo.split(","));
        Map parm = new HashMap();
        parm.put("stowageList",stowageList);

        List<StowageVO>  list = hsOptArriveService.queryStowageArriveList(parm);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                StowageVO stowage = list.get(i);
                Map searchMap = new HashMap();
                searchMap.put("operationId", stowage.getOperationId());
                stowage.setArriveEwbVO(hsOptArriveService.queryPrintArriveEwb(searchMap));
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("companyName", LoginDetailUtils.getCompanyName());
        if(StringUtils.isEmpty(String.valueOf(json.get("data")))){
            map.put("pictureUrl","../api/static/logo.png");
        }else {
            map.put("pictureUrl", json.get("data"));
        }
        return FreemarkUtils.getPrintTemplate( configuration, "arrivePrint", map);
    }

}
